
package com.rt.schedulenew.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rt.schedulebase.dto.DictExamItemDto;
import com.rt.schedulebase.dto.DictExamItemMobileNoticeItemDto;
import com.rt.schedulebase.dto.DictUsersDto;
import com.rt.schedulebase.entity.DictExamItem;
import com.rt.schedulebase.entity.ExamSyslog;
import com.rt.schedulebase.entity.commonentity.PageResultUtil;
import com.rt.schedulebase.excel.Custemhandler;
import com.rt.schedulebase.excel.DictExamItemExcel;
import com.rt.schedulebase.mapper.DictExamItemMapper;
import com.rt.schedulenew.api.IDictExamItemService;
import com.rt.schedulenew.api.IExamSyslogService;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import com.rt.schedulenew.utils.base.NoticeDto;
import com.rt.schedulenew.utils.base.XmlUtil;
import com.rt.schedulenew.utils.global.BusinessException;
import com.rt.schedulenew.utils.global.ErrorCode;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.util.DateUtil;
import com.rt.schedulenew.utils.util.JsonUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class DictExamItemServiceImpl extends ServiceImpl<DictExamItemMapper, DictExamItem> implements IDictExamItemService {
    @Override
    public DictExamItem getInfo(DictExamItemDto dto) {
        QueryWrapper<DictExamItem> qw = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("ITEM_NAME", dto.getItemName());
        map.put("ITEM_CODE", dto.getItemCode());
        map.put("EXAM_CLASS", dto.getExamClass());
        map.put("EXAM_SUB_CLASS", dto.getExamSubClass());
        qw.allEq(map, false);
        if (StringUtils.isNotBlank(dto.getNotNullDayscope())) {
            qw.isNotNull("GESTINFO_DAYSCOPE");
        }
        return baseMapper.selectOne(qw);
    }

    @Transactional
    @Override
    public boolean insertBatch(List<DictExamItemDto> list) {
        List<String> descList = new ArrayList<String>();
        for (DictExamItemDto dto : list) {
            UpdateWrapper<DictExamItem> qw = new UpdateWrapper<>();
            qw.eq("ITEM_NAME", dto.getItemName());
            qw.eq("EXAM_CLASS", dto.getExamClass());
            qw.eq("ITEM_CODE", dto.getItemCode());
            if (StringUtils.isNotBlank(dto.getBeforeExamSubClass())) {
                qw.eq("EXAM_SUB_CLASS", dto.getBeforeExamSubClass());
            }
            int count = baseMapper.selectCount(qw);
            if (count == 0) {
                retBool(baseMapper.insert(dto));
                //insertSelective(dto);
            }
        }
        return true;
    }


    private static String OPERATE_TAG_SAVE = "SAVE";
    private static String OPERATE_TAG_DELETE = "DELETE";
    private static String OPERATE_TAG_UPDATE = "UPDATE";
    private static String NOTICE_TYPE_ZERO = "0";
    private static String NOTICE_TYPE_ONE = "1";
    private static String NOTICE_TYPE_TWO = "2";

    @Autowired
    private IExamSyslogService examSyslogService;
//
//    @Override
//    public boolean insertSelective(DictExamItem dictExamItem) {
//        return retBool(baseMapper.insert(dictExamItem));
//    }
//
//    @Override
//    public boolean deleteByPrimaryKey(String key) {
//        return retBool(baseMapper.deleteById(key));
//    }
//
//    @Override
//    public boolean updateByPrimaryKeySelective(DictExamItem dictExamItem) {
//        return retBool(baseMapper.updateById(dictExamItem));
//    }
//
//    @Override
//    public DictExamItem selectByPrimaryKey(String key) {
//        return baseMapper.selectById(key);
//    }

    @Override
    public List<DictExamItem> getList(DictExamItemDto dto) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ITEM_CODE", dto.getItemCode());
        map.put("SETUP_USER", dto.getSetupUser());
        map.put("INPUT_CODE", dto.getInputCode());
        QueryWrapper<DictExamItem> qw = new QueryWrapper<>();
        qw.allEq(map, false);
        qw.like("ITEM_NAME", dto.getItemName().trim());
        if (StringUtils.isNotBlank(dto.getExamClass())) {
            qw.in("EXAM_CLASS", CommonUtil.split2List(dto.getExamClass()));
        }
        if (StringUtils.isNotBlank(dto.getExamSubClass())) {
            qw.in("EXAM_SUB_CLASS", CommonUtil.split2List(dto.getExamSubClass()));
        }
        List<DictExamItem> list = baseMapper.selectList(qw);
        return list;
    }

    @Override
    public List<DictExamItem> getListAll() {
        return baseMapper.selectList(null);
    }

    @Override
    public boolean delete(DictExamItem dictExamItem) {
        UpdateWrapper<DictExamItem> uw = new UpdateWrapper<>();
        Map<String, Object> map = new HashMap<String, Object>();
        uw.allEq(map, false);
        return retBool(baseMapper.delete(uw));
    }

    @Override
    public boolean update(DictExamItemDto dictExamItem) {
        dictExamItem.setSetupDate(DateUtil.getCurrDateStr() + " " + DateUtil.getCurrentTime());
        dictExamItem.setFlags(CommonUtil.convertItemFlags(dictExamItem.getItemFlags()));
        UpdateWrapper<DictExamItem> uw = new UpdateWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("ITEM_CODE", dictExamItem.getItemCode());
        map.put("ITEM_NAME", dictExamItem.getItemName());
        map.put("EXAM_CLASS", dictExamItem.getExamClass());
        map.put("EXAM_SUB_CLASS", dictExamItem.getBeforeExamSubClass());
        uw.allEq(map, false);
        if (StringUtils.isBlank(dictExamItem.getIsBatch())) {
            uw.set(dictExamItem.getBeginTime() == null, "BEGIN_TIME", "");
            uw.set(dictExamItem.getBeginDays() == null, "BEGIN_DAYS", "");
            uw.set(dictExamItem.getScheduleOrder() == null, "SCHEDULE_ORDER", "");
            uw.set(dictExamItem.getOrgans() == null, "ORGANS", "");
            uw.set(StringUtils.isBlank(dictExamItem.getGestinfoDayscope()), "GESTINFO_DAYSCOPE", "");
            uw.set(StringUtils.isBlank(dictExamItem.getNotice()), "NOTICE", "");
            uw.set(StringUtils.isBlank(dictExamItem.getExamRequire()), "EXAM_REQUIRE", "");
        }
        return retBool(baseMapper.update(dictExamItem, uw));
    }


    @Override
    public JsonResult getListPage(DictExamItemDto dto) {
        Page<DictExamItemDto> page = new Page<>();
        if (dto.getPageNo() != null) {
            page = PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        }
        if (StringUtils.isNotBlank(dto.getExamClass())) {
            dto.setExamClassList(CommonUtil.split2List(dto.getExamClass()));
            dto.setExamClass(null);
        }
        if (StringUtils.isNotBlank(dto.getExamSubClass())) {
            dto.setExamSubClassList(CommonUtil.split2List(dto.getExamSubClass()));
            dto.setExamSubClass(null);
        }
        if (dto.getItemFlags() != null) {
            String flags = CommonUtil.convertItemFlagsCondition(dto.getItemFlags());
            dto.setFlags(flags);
        }
        List<DictExamItemDto> list = baseMapper.getItemList(dto);
        for (DictExamItemDto examItemDto : list) {
            examItemDto.setItemFlags(CommonUtil.flag2itemFlag(examItemDto.getFlags()));
        }
        JsonResult jsonResult = PageResultUtil.success(ErrorCode.SUCCESS.getValue(), list, page);
        return jsonResult;
    }

    @Transactional
    @Override
    public boolean updateBatch(List<DictExamItemDto> list, DictUsersDto dictUsersDto) {
        for (DictExamItemDto dto : list) {
            if (list.size() > 1) {
                dto.setIsBatch("1");
            }
            String examSubClass = dto.getExamSubClass();
            dto.setExamSubClass(dto.getBeforeExamSubClass());
            DictExamItem oldItem = getInfo(dto);
            dto.setExamSubClass(examSubClass);
            update(dto);
            DictExamItem newItem = getInfo(dto);
            oldItem.setFlags(CommonUtil.flag2String(oldItem.getFlags()));
            newItem.setFlags(CommonUtil.flag2String(newItem.getFlags()));
            ExamSyslog examSyslog = new ExamSyslog();
            examSyslog.setModuleName(ConstantsUtil.ModuleName.DICT_EXAM_ITEM.getName());
            examSyslog.setOperateName(ConstantsUtil.OperateName.UPDATE.getDesc());
            String keyName = dto.getItemName();
            examSyslogService.insertSysLog(examSyslog, dictUsersDto, oldItem, newItem, keyName);
        }
        return true;
    }

    @Override
    public Map<String, NoticeDto> getNotice(DictExamItemDto dto) {
        DictExamItem info = getInfo(dto);
        if (info == null) {
            return null;
        }
        String notice = info.getNotice();
        if (StringUtils.isBlank(notice) || !notice.contains("<notices>")) {
            return null;
        }
        String all = notice.replace("<notices>", "");
        String replace = all.replace("</notices>", "");
        String replace2 = replace.replace("<notice>", "=====");
        String replace3 = replace2.replace("</notice>", "");
        List<String> strToList = CommonUtil.strToList(replace3, "=====");
        List<NoticeDto> list = new ArrayList<NoticeDto>();
        for (String string : strToList) {
            String taboo = "";
            if (StringUtils.isBlank(string)) {
                continue;
            }
            if (string.contains("<taboo>")) {
                String str = string;
                taboo = str.replaceAll("<text>无</text>", "").replaceAll("<taboo>", "").replaceAll("</taboo>", "");
                taboo = taboo.replaceAll("&lt;", "<").replaceAll("&gt;", ">");
            }
            if (string.contains("<taboo>")) {
                NoticeDto noticeDto = new NoticeDto();
                noticeDto.setTaboo(taboo);
                list.add(noticeDto);
            } else {
                string = "<notice>" + string + "</notice>";
                JSONObject jsonObject = XmlUtil.xml2JSON(string);
                String noticeStr = jsonObject.toString();
                NoticeDto noticeDto2 = (NoticeDto) JSONObject.parseObject(noticeStr, NoticeDto.class);
                list.add(noticeDto2);
            }
        }
        Map<String, NoticeDto> map = new HashMap<String, NoticeDto>();
        int index = 0;
        Iterator<NoticeDto> iterator2 = list.iterator();
        while (iterator2.hasNext()) {
            NoticeDto noticeDto = iterator2.next();
            String key = index + "";
            map.put(key, noticeDto);
            ++index;
        }
        return map;
    }

    @Override
    public List<NoticeDto> getNoticeList(DictExamItemDto dto) {
        Map<String, NoticeDto> noticeMap = getNotice(dto);
        if (noticeMap == null || noticeMap.size() == 0) {
            return null;
        }
        String noticeType = dto.getNoticeType();
        List<NoticeDto> list = new ArrayList<NoticeDto>();
        for (int size = noticeMap.size(), i = 0; i < size; ++i) {
            String key = i + "";
            NoticeDto noticeDto = noticeMap.get(key);
            if (noticeDto != null) {
                noticeDto.setSortNo(key);
                boolean isText = isText(noticeDto);
                if (noticeType.equals("0") && isText) {
                    list.add(noticeDto);
                }
                boolean isSms = isSms(noticeDto);
                if (noticeType.equals("1") && isSms) {
                    list.add(noticeDto);
                }
                boolean tabooNoNull = isTextOrSmsIsNull(noticeDto);
                if (noticeType.equals("2") && tabooNoNull) {
                    String taboo = noticeDto.getTaboo();
                    list.add(noticeDto);
                }
            }
        }
        return list;
    }

    @Override
    public List<DictExamItemMobileNoticeItemDto> getMobileNoticeList(DictExamItemDto itemDto) {
        List<DictExamItemMobileNoticeItemDto> result = null;
        DictExamItem examItem = getInfo(itemDto);
        if (ObjectUtils.isNotEmpty(examItem) && StringUtils.isNoneBlank(examItem.getMobileNotice())) {
            result = JsonUtil.toList(examItem.getMobileNotice(), DictExamItemMobileNoticeItemDto.class);
        }
        return result;
    }

    @Override
    public boolean saveMobileNoticeList(String itemCode, List<DictExamItemMobileNoticeItemDto> items) {
        DictExamItemDto itemDto = new DictExamItemDto();
        itemDto.setItemCode(itemCode);
        DictExamItem examItem = getInfo(itemDto);
        if (ObjectUtils.isNotEmpty(examItem)) {
            UpdateWrapper<DictExamItem> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("MOBILE_NOTICE", JsonUtil.toJson(items));
            updateWrapper.eq("ITEM_CODE", itemCode);
            baseMapper.update(null, updateWrapper);
            return true;
        }
        return false;
    }

    private boolean isText(NoticeDto noticeDto) {
        return StringUtils.isNotBlank(noticeDto.getMinDays()) || StringUtils.isNotBlank(noticeDto.getMaxDays()) || StringUtils.isNotBlank(noticeDto.getPatientSource());
    }

    private boolean isSms(NoticeDto noticeDto) {
        return StringUtils.isNotBlank(noticeDto.getSmsDays()) || StringUtils.isNotBlank(noticeDto.getSmsApmStartTime()) || StringUtils.isNotBlank(noticeDto.getSmsApmEndTime()) || StringUtils.isNotBlank(noticeDto.getSmsTime()) || StringUtils.isNotBlank(noticeDto.getSmsContent());
    }

    private boolean isTextOrSmsIsNull(NoticeDto noticeDto) {
        return !StringUtils.isNotBlank(noticeDto.getSmsContent()) && !StringUtils.isNotBlank(noticeDto.getMaxDays()) && !StringUtils.isNotBlank(noticeDto.getPatientSource()) && !StringUtils.isNotBlank(noticeDto.getMinDays()) && !StringUtils.isNotBlank(noticeDto.getSmsApmEndTime()) && !StringUtils.isNotBlank(noticeDto.getSmsDays()) && !StringUtils.isNotBlank(noticeDto.getSmsTime()) && !StringUtils.isNotBlank(noticeDto.getSmsApmStartTime());
    }

    @Override
    public Boolean saveOrUpdateNotice(DictExamItemDto dto) {
        Map<String, NoticeDto> noticeDtoMap = getNotice(dto);
        Integer sortNo = dto.getSortNo();
        NoticeDto dtoNoticeDto = dto.getNoticeDto();
        String operateTag = dto.getOperateTag();
        String noticeType = dto.getNoticeType();
        if (operateTag.equals("SAVE") && (noticeDtoMap == null || noticeDtoMap.size() == 0)) {
            String text = dtoNoticeDto.getText();
            if (StringUtils.isBlank(text)) {
                dtoNoticeDto.setText("无");
            }
            String toXml = XmlUtil.objectToXml(dtoNoticeDto, "<notice>", "</notice>");
            StringBuilder builder = new StringBuilder();
            builder.append("<notices>");
            builder.append(toXml).append("</notices>");
            String noticeStr = builder.toString();
            DictExamItem info = getInfo(dto);
            info.setNotice(noticeStr);
            DictExamItemDto dictExamItemDto = new DictExamItemDto();
            try {
                BeanUtils.copyProperties(info, dictExamItemDto);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return update(dictExamItemDto);
        }
        int size = 0;
        if (noticeDtoMap != null) {
            size = noticeDtoMap.size();
        }
        NoticeDto noticeDto = noticeDtoMap.get(sortNo + "");
        if (operateTag.equals("DELETE")) {
            noticeDtoMap.put(sortNo + "", null);
        } else {
            if (dtoNoticeDto == null) {
                throw new BusinessException("注意事项更新或新增的内容不能为空");
            }
            if (operateTag.equals("SAVE")) {
                if ("2".equals(noticeType)) {
                    boolean isNotNull = checkTabooNotNull(noticeDtoMap);
                    if (isNotNull) {
                        throw new BusinessException("只存在禁忌信息的节点已存在");
                    }
                }
                sortNo = size;
                ++size;
                noticeDto = new NoticeDto();
            }
            encapsulationNotice(dtoNoticeDto, noticeDto);
            noticeDtoMap.put(sortNo + "", noticeDto);
            if ("UPDATE".equals(operateTag) && "2".equals(noticeType)) {
                String taboo = dtoNoticeDto.getTaboo();
                if (StringUtils.isBlank(taboo)) {
                    noticeDtoMap.put(sortNo + "", null);
                }
            }
        }
        StringBuilder builder = new StringBuilder();
        builder.append("<notices>");
        for (int i = 0; i < size; ++i) {
            String key = i + "";
            NoticeDto notice = noticeDtoMap.get(key);
            if (notice != null) {
                notice.setSortNo(null);
                String text2 = notice.getText();
                if (StringUtils.isBlank(text2)) {
                    notice.setText("无");
                }
                String toXml2 = XmlUtil.objectToXml(notice, "<notice>", "</notice>");
                builder.append(toXml2);
            }
        }
        builder.append("</notices>");
        String toStringNotice = builder.toString();
        DictExamItem info = getInfo(dto);
        info.setNotice(toStringNotice);
        DictExamItemDto dictExamItemDto = new DictExamItemDto();
        try {
            BeanUtils.copyProperties(info, dictExamItemDto);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return update(dictExamItemDto);
    }

    @Transactional
    @Override
    public Boolean noticeBatchSave(List<DictExamItemDto> dtoList) {
        if (dtoList == null || dtoList.size() == 0) {
            return true;
        }
        for (DictExamItemDto itemDto : dtoList) {
            String noticeType = itemDto.getNoticeType();
            int size = 0;
            Map<String, NoticeDto> noticeDtoMap = getNotice(itemDto);
            if (noticeDtoMap != null && noticeDtoMap.size() != 0) {
                size = noticeDtoMap.size();
            }
            if (noticeDtoMap == null || noticeDtoMap.size() == 0) {
                noticeDtoMap = new HashMap<String, NoticeDto>();
            }
            List<NoticeDto> noticeList = itemDto.getNoticeList();
            if (noticeList != null) {
                if (noticeList.size() == 0) {
                    continue;
                }
                if ("2".equals(noticeType)) {
                    NoticeDto noticeDto = noticeList.get(0);
                    if (noticeDtoMap.size() != 0) {
                        itemDto.setNoticeType(noticeType);
                        List<NoticeDto> list = getNoticeList(itemDto);
                        String text = noticeDto.getTaboo();
                        if (StringUtils.isBlank(text)) {
                            noticeDto.setText(text);
                        }
                        if (list != null && list.size() != 0) {
                            NoticeDto notice = list.get(0);
                            String sortNo = notice.getSortNo();
                            noticeDtoMap.put(sortNo, noticeDto);
                        } else {
                            noticeDtoMap.put(size + "", noticeDto);
                        }
                    }
                } else {
                    for (NoticeDto noticeDto2 : noticeList) {
                        String text = noticeDto2.getTaboo();
                        if (StringUtils.isBlank(text)) {
                            text = "无";
                        }
                        noticeDto2.setText(text);
                        noticeDtoMap.put(size + "", noticeDto2);
                        ++size;
                    }
                }
                String mapToXml = XmlUtil.mapToXml(noticeDtoMap, "<notices>", "</notices>", "<notice>", "</notice>");
                DictExamItem info = getInfo(itemDto);
                if (info == null) {
                    continue;
                }
                info.setNotice(mapToXml);
                DictExamItemDto dictExamItemDto = new DictExamItemDto();
                try {
                    BeanUtils.copyProperties(info, dictExamItemDto);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
                update(dictExamItemDto);
            }
        }
        return true;
    }

    @Override
    public void getTemplate(HttpServletResponse response) {
        try {
            String fileName = URLEncoder.encode("检查项目导入模板.xlsx", "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            String sheetName = "检查项目导入模板";

            List<DictExamItemExcel> list = new ArrayList<>();

            DictExamItemExcel dictExamItemExcel = new DictExamItemExcel();
            dictExamItemExcel.setItemName("腹部超声检查");
            dictExamItemExcel.setItemCode("cc000619");
            dictExamItemExcel.setOrgans(1.0);
            dictExamItemExcel.setExamClass("超声");
            dictExamItemExcel.setExamSubClass("腹部");
            dictExamItemExcel.setCalmDown("是");
            dictExamItemExcel.setEnhance("否");
            dictExamItemExcel.setFasting("是");
            dictExamItemExcel.setHoldBackUrine("是");
            dictExamItemExcel.setPuncture("否");
            dictExamItemExcel.setMedicalTechnologyAppointment("是");
            dictExamItemExcel.setReservationCenter("是");
            dictExamItemExcel.setClinicalClinic("是");
            dictExamItemExcel.setClinicalInpatient("是");
            dictExamItemExcel.setSelfServiceAppointment("否");
            dictExamItemExcel.setMobileAppointment("是");
            dictExamItemExcel.setNoSelfCheckIn("否");
            dictExamItemExcel.setBeginTime(5);
            dictExamItemExcel.setBeginDays(365);
            dictExamItemExcel.setBeginGestinfoDayscope(0);
            dictExamItemExcel.setEndGestinfoDayscope(350);
            dictExamItemExcel.setExamRequire("检查前注意饮食");
            dictExamItemExcel.setNotice("检查前注意饮食");
            list.add(dictExamItemExcel);

            EasyExcel.write(response.getOutputStream(), DictExamItemExcel.class).sheet(sheetName)
                    .needHead(true)
                    .registerWriteHandler(Custemhandler.getStyleStrategy())
                    .doWrite(list);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @Transactional
    @Override
    public JsonResult batchImportExamItem(MultipartFile file) {
        String fileType = Objects.requireNonNull(file.getOriginalFilename())
                .substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();
        if (!".xlsx".equals(fileType)) {
            return JsonResultUtil.failure("上传模板格式不正确，必须是xlsx类型！");
        }

        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            // 获取工作簿
            Sheet sheet = workbook.getSheetAt(0);

            List<DictExamItemExcel> list = new ArrayList<>();
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                DictExamItemExcel dictExamItemExcel = new DictExamItemExcel();
                try {
                    // 按照下标获取当前行的单元格
                    dictExamItemExcel.setItemName(String.valueOf(row.getCell(0)));
                    if (dictExamItemExcel.getItemName() != null) {
                        dictExamItemExcel.setItemName(dictExamItemExcel.getItemName().replace(" ", ""));
                    }
                    if (dictExamItemExcel.getItemName() == null || dictExamItemExcel.getItemName().isEmpty()) {
                        return JsonResultUtil.failure("导入失败：第" + i + "行，项目名称不能为空");
                    }

                    dictExamItemExcel.setItemCode(String.valueOf(row.getCell(1)));
                    if (dictExamItemExcel.getItemCode() != null) {
                        dictExamItemExcel.setItemCode(dictExamItemExcel.getItemCode().replace(" ", ""));
                    }
                    if (dictExamItemExcel.getItemCode() == null || dictExamItemExcel.getItemCode().isEmpty()) {
                        return JsonResultUtil.failure("导入失败：第" + i + "行，项目编码不能为空");
                    }

                    dictExamItemExcel.setOrgans(Double.valueOf(String.valueOf(row.getCell(2))));

                    dictExamItemExcel.setExamClass(String.valueOf(row.getCell(3)));
                    if (dictExamItemExcel.getExamClass() != null) {
                        dictExamItemExcel.setExamClass(dictExamItemExcel.getExamClass().replace(" ", ""));
                    }
                    if (dictExamItemExcel.getExamClass() == null || dictExamItemExcel.getExamClass().isEmpty()) {
                        return JsonResultUtil.failure("导入失败：第" + i + "行，检查类别不能为空");
                    }

                    dictExamItemExcel.setExamSubClass(String.valueOf(row.getCell(4)));
                    if (dictExamItemExcel.getExamSubClass() != null) {
                        dictExamItemExcel.setExamSubClass(dictExamItemExcel.getExamSubClass().replace(" ", ""));
                    }

                    dictExamItemExcel.setCalmDown(String.valueOf(row.getCell(5)));
                    if (dictExamItemExcel.getCalmDown() != null) {
                        dictExamItemExcel.setCalmDown(dictExamItemExcel.getCalmDown().replace(" ", ""));
                        if (dictExamItemExcel.getCalmDown().length() > 1 || (!dictExamItemExcel.getCalmDown().equals("是") && !dictExamItemExcel.getCalmDown().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【镇静】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setEnhance(String.valueOf(row.getCell(6)));
                    if (dictExamItemExcel.getEnhance() != null) {
                        dictExamItemExcel.setEnhance(dictExamItemExcel.getEnhance().replace(" ", ""));
                        if (dictExamItemExcel.getEnhance().length() > 1 || (!dictExamItemExcel.getEnhance().equals("是") && !dictExamItemExcel.getEnhance().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【增强】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setFasting(String.valueOf(row.getCell(7)));
                    if (dictExamItemExcel.getFasting() != null) {
                        dictExamItemExcel.setFasting(dictExamItemExcel.getFasting().replace(" ", ""));
                        if (dictExamItemExcel.getFasting().length() > 1 || (!dictExamItemExcel.getFasting().equals("是") && !dictExamItemExcel.getFasting().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【空腹】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setHoldBackUrine(String.valueOf(row.getCell(8)));
                    if (dictExamItemExcel.getHoldBackUrine() != null) {
                        dictExamItemExcel.setHoldBackUrine(dictExamItemExcel.getHoldBackUrine().replace(" ", ""));
                        if (dictExamItemExcel.getHoldBackUrine().length() > 1 || (!dictExamItemExcel.getHoldBackUrine().equals("是") && !dictExamItemExcel.getHoldBackUrine().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【憋尿】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setPuncture(String.valueOf(row.getCell(9)));
                    if (dictExamItemExcel.getPuncture() != null) {
                        dictExamItemExcel.setPuncture(dictExamItemExcel.getPuncture().replace(" ", ""));
                        if (dictExamItemExcel.getPuncture().length() > 1 || (!dictExamItemExcel.getPuncture().equals("是") && !dictExamItemExcel.getPuncture().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【穿刺】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setMedicalTechnologyAppointment(String.valueOf(row.getCell(10)));
                    if (dictExamItemExcel.getMedicalTechnologyAppointment() != null) {
                        dictExamItemExcel.setMedicalTechnologyAppointment(dictExamItemExcel.getMedicalTechnologyAppointment().replace(" ", ""));
                        if (dictExamItemExcel.getMedicalTechnologyAppointment().length() > 1 || (!dictExamItemExcel.getMedicalTechnologyAppointment().equals("是") && !dictExamItemExcel.getMedicalTechnologyAppointment().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【医技预约】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setReservationCenter(String.valueOf(row.getCell(11)));
                    if (dictExamItemExcel.getReservationCenter() != null) {
                        dictExamItemExcel.setReservationCenter(dictExamItemExcel.getReservationCenter().replace(" ", ""));
                        if (dictExamItemExcel.getReservationCenter().length() > 1 || (!dictExamItemExcel.getReservationCenter().equals("是") && !dictExamItemExcel.getReservationCenter().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【预约中心】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setClinicalClinic(String.valueOf(row.getCell(12)));
                    if (dictExamItemExcel.getClinicalClinic() != null) {
                        dictExamItemExcel.setClinicalClinic(dictExamItemExcel.getClinicalClinic().replace(" ", ""));
                        if (dictExamItemExcel.getClinicalClinic().length() > 1 || (!dictExamItemExcel.getClinicalClinic().equals("是") && !dictExamItemExcel.getClinicalClinic().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【临床门诊】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setClinicalInpatient(String.valueOf(row.getCell(13)));
                    if (dictExamItemExcel.getClinicalInpatient() != null) {
                        dictExamItemExcel.setClinicalInpatient(dictExamItemExcel.getClinicalInpatient().replace(" ", ""));
                        if (dictExamItemExcel.getClinicalInpatient().length() > 1 || (!dictExamItemExcel.getClinicalInpatient().equals("是") && !dictExamItemExcel.getClinicalInpatient().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【临床住院】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setSelfServiceAppointment(String.valueOf(row.getCell(14)));
                    if (dictExamItemExcel.getSelfServiceAppointment() != null) {
                        dictExamItemExcel.setSelfServiceAppointment(dictExamItemExcel.getSelfServiceAppointment().replace(" ", ""));
                        if (dictExamItemExcel.getSelfServiceAppointment().length() > 1 || (!dictExamItemExcel.getSelfServiceAppointment().equals("是") && !dictExamItemExcel.getSelfServiceAppointment().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【自助预约】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setMobileAppointment(String.valueOf(row.getCell(15)));
                    if (dictExamItemExcel.getMobileAppointment() != null) {
                        dictExamItemExcel.setMobileAppointment(dictExamItemExcel.getMobileAppointment().replace(" ", ""));
                        if (dictExamItemExcel.getMobileAppointment().length() > 1
                                || (!dictExamItemExcel.getMobileAppointment().equals("是")
                                && !dictExamItemExcel.getMobileAppointment().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【移动预约】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setNoSelfCheckIn(String.valueOf(row.getCell(16)));
                    if (dictExamItemExcel.getNoSelfCheckIn() != null) {
                        dictExamItemExcel.setNoSelfCheckIn(dictExamItemExcel.getNoSelfCheckIn().replace(" ", ""));
                        if (dictExamItemExcel.getNoSelfCheckIn().length() > 1 || (!dictExamItemExcel.getNoSelfCheckIn().equals("是") && !dictExamItemExcel.getNoSelfCheckIn().equals("否"))) {
                            return JsonResultUtil.failure("导入失败：第" + i + "行，【不能自助报到】参数格式不正确");
                        }
                    }

                    dictExamItemExcel.setBeginTime(new BigDecimal(String.valueOf(row.getCell(17))).intValue());
                    dictExamItemExcel.setBeginDays(new BigDecimal(String.valueOf(row.getCell(18))).intValue());
                    dictExamItemExcel.setBeginGestinfoDayscope(new BigDecimal(String.valueOf(row.getCell(19))).intValue());
                    dictExamItemExcel.setEndGestinfoDayscope(new BigDecimal(String.valueOf(row.getCell(20))).intValue());


                    dictExamItemExcel.setExamRequire(String.valueOf(row.getCell(21)));
                    if (dictExamItemExcel.getExamRequire() != null) {
                        dictExamItemExcel.setExamRequire(dictExamItemExcel.getExamRequire().replace(" ", ""));
                    }

                    dictExamItemExcel.setNotice(String.valueOf(row.getCell(22)));
                    if (dictExamItemExcel.getNotice() != null) {
                        dictExamItemExcel.setNotice(dictExamItemExcel.getNotice().replace(" ", ""));
                    }
                    list.add(dictExamItemExcel);
                } catch (Exception e) {
                    log.error("参数解析失败:" + e.getMessage(), e);
                    return JsonResultUtil.failure("参数解析失败,原因是excel文件的第" + i + "行。" + e.getMessage());
                }
            }
            // 根据指定属性分组，并统计数量（key：指定属性，value：数量）
            Map<String, Long> mapGroup = list.stream().collect(Collectors.groupingBy(item -> item.getItemCode(), Collectors.counting()));

            // 筛选Map中value大于1的key
            Stream<Object> stringStream = mapGroup.entrySet().stream().filter(item -> item.getValue() > 1).map(item -> item.getKey());
            //final String[] repeatItemCode = {""};
            StringBuilder repeatItemCode = new StringBuilder();
            stringStream.forEach(str -> {
                //repeatItemCode[0] += str + ",";
                repeatItemCode.append(str + ",");
            });
            if (!repeatItemCode.toString().isEmpty()) {
                return JsonResultUtil.failure("导入失败：导入数据中存在重复的项目编号，【" + repeatItemCode.toString().substring(0, repeatItemCode.toString().length() - 1) + "】");
            }
            list.forEach(item -> {
                DictExamItem dictExamItem = new DictExamItem();
                try {
                    BeanUtils.copyProperties(item, dictExamItem);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
                dictExamItem.setGestinfoDayscope(String.valueOf(item.getBeginGestinfoDayscope() + "~" + item.getEndGestinfoDayscope()));

                dictExamItem.setFlags("10000001111000000000");// 初始编码
                String[] split = dictExamItem.getFlags().split("");
                if (item.getCalmDown().equals("是")) {// 镇静
                    split[1] = "1";
                }
                if (item.getEnhance().equals("是")) {// 增强
                    split[2] = "1";
                }
                if (item.getFasting().equals("是")) {// 空腹
                    split[3] = "1";
                }
                if (item.getHoldBackUrine().equals("是")) {// 憋尿
                    split[4] = "1";
                }
                if (item.getPuncture().equals("是")) {// 穿刺
                    split[5] = "1";
                }
                if (item.getNoSelfCheckIn().equals("是")) {// 不能自助报到
                    split[6] = "1";
                }
                if (item.getMedicalTechnologyAppointment().equals("是")) {// 医技预约
                    split[0] = "2"; // 只能前台预约
                    if (item.getReservationCenter().equals("是")) {// 预约中心
                        split[0] = "0";
                        split[7] = "0"; //  预约中心预约
                    }
                    if (item.getClinicalClinic().equals("是")) {// 临床门诊
                        split[0] = "0";
                        split[8] = "3"; // 临床门诊 不能临床住院
                        if (item.getClinicalInpatient().equals("是")) {// 临床住院
                            split[8] = "0"; // 能临床门诊 能临床住院
                        }
                    }
                    if (item.getClinicalInpatient().equals("是")) {// 临床住院
                        split[0] = "0";
                        split[8] = "2";
                        if (item.getClinicalClinic().equals("是")) {// 临床门诊
                            split[8] = "0";
                        }
                    }
                    if (item.getSelfServiceAppointment().equals("是")) {// 自助预约
                        split[0] = "0";
                        split[9] = "0";
                    }
                    if (item.getMobileAppointment().equals("是")) {// 移动预约
                        split[0] = "0";
                        split[10] = "0";
                    }
                }
                dictExamItem.setFlags(StringUtils.join(split, ""));
                QueryWrapper<DictExamItem> objectQueryWrapper = new QueryWrapper<>();
                objectQueryWrapper.eq("ITEM_CODE", dictExamItem.getItemCode());
                DictExamItem examItem = baseMapper.selectOne(objectQueryWrapper);
                if (examItem != null) {
                    throw new BusinessException("导入失败，项目编号【" + examItem.getItemCode() + "】已存在无法重复插入。");
                }
                baseMapper.insert(dictExamItem);
            });

        } catch (IOException e) {
            log.error("导入失败：" + e.getMessage(), e);
            return JsonResultUtil.failure("导入失败：" + e.getMessage());
        }
        return JsonResultUtil.success();
    }

    private boolean checkTabooNotNull(Map<String, NoticeDto> noticeDtoMap) {
        if (noticeDtoMap == null || noticeDtoMap.size() == 0) {
            return false;
        }
        Set<String> keys = noticeDtoMap.keySet();
        for (String key : keys) {
            NoticeDto noticeDto = noticeDtoMap.get(key);
            boolean textOrSmsIsNull = isTextOrSmsIsNull(noticeDto);
            if (textOrSmsIsNull) {
                return true;
            }
        }
        return false;
    }

    private void encapsulationNotice(NoticeDto dtoNoticeDto, NoticeDto noticeDto) {
        String maxDays = dtoNoticeDto.getMaxDays();
        if (StringUtils.isNotBlank(maxDays)) {
            noticeDto.setMaxDays(maxDays);
        }
        String minDays = dtoNoticeDto.getMinDays();
        if (StringUtils.isNotBlank(minDays)) {
            noticeDto.setMinDays(minDays);
        }
        String patientSource = dtoNoticeDto.getPatientSource();
        if (StringUtils.isNotBlank(patientSource)) {
            noticeDto.setPatientSource(patientSource);
        }
        String smsApmEndTime = dtoNoticeDto.getSmsApmEndTime();
        if (StringUtils.isNotBlank(smsApmEndTime)) {
            noticeDto.setSmsApmEndTime(smsApmEndTime);
        }
        String smsApmStartTime = dtoNoticeDto.getSmsApmStartTime();
        if (StringUtils.isNotBlank(smsApmStartTime)) {
            noticeDto.setSmsApmStartTime(smsApmStartTime);
        }
        String smsContent = dtoNoticeDto.getSmsContent();
        if (StringUtils.isNotBlank(smsContent)) {
            noticeDto.setSmsContent(smsContent);
        }
        String smsDays = dtoNoticeDto.getSmsDays();
        if (StringUtils.isNotBlank(smsDays)) {
            noticeDto.setSmsDays(smsDays);
        }
        String smsTime = dtoNoticeDto.getSmsTime();
        if (StringUtils.isNotBlank(smsTime)) {
            noticeDto.setSmsTime(smsTime);
        }
        String taboo = dtoNoticeDto.getTaboo();
        noticeDto.setTaboo(taboo);
        String text = dtoNoticeDto.getText();
        if (StringUtils.isNotBlank(text)) {
            noticeDto.setText(text);
        }
    }
}
